package first.group.ssh.hostkey;

import first.group.ssh.hostkey.HostKeyAlgorithm.HostKey;
import first.group.ssh.packet.PacketParser;
import first.group.ssh.packet.reader.StringReader;
import java.io.IOException;
import java.nio.ByteBuffer;

public class HostKeyParser {
    private static HostKey<? extends HostKeyAlgorithm> parseHostKeyData(ByteBuffer buffer) throws IOException {
        var type = StringReader.readString(buffer);
        if (type == null) {
            return null;
        }
        var algo = HostKeyAlgorithm.algos
                .stream()
                .filter(o -> o.getName().equals(type))
                .findFirst()
                .get();
        var key = algo.getKeyParser().parse(buffer);
        if (key == null) {
            return null;
        }
        return key;
    }
    
    public static HostKey<? extends HostKeyAlgorithm> parseHostKey(ByteBuffer buffer) throws IOException {
        if (!PacketParser.bufferRemains(buffer, 4)) {
            return null;
        }
        var len = buffer.getInt();
        if (!PacketParser.bufferRemains(buffer, len)) {
            return null;
        }
        var origLimit = buffer.limit();
        buffer.limit(buffer.position() + len);
        
        var result = parseHostKeyData(buffer);
        buffer.limit(origLimit);
        
        return result;
    }
}
